package com.lzw.blog.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzw.blog.admin.mapper.ArticleMapper;
import com.lzw.blog.admin.mapper.CommentMapper;
import com.lzw.blog.admin.mapper.UserMapper;
import com.lzw.blog.admin.model.params.PageParam;
import com.lzw.blog.admin.pojo.Article;
import com.lzw.blog.admin.pojo.Comment;
import com.lzw.blog.admin.pojo.User;
import com.lzw.blog.admin.vo.CommentVo;
import com.lzw.blog.admin.vo.PageResult;
import com.lzw.blog.admin.vo.Result;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CommentsService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private UserMapper userMapper;



    public Result listComment(PageParam pageParam) {
        /**
         * 要的数据，管理台 表的所有的字段 Permission
         * 分页查询
         */
        Page<Comment> page = new Page<>(pageParam.getCurrentPage(), pageParam.getPageSize());

        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(pageParam.getQueryString())) {
            queryWrapper.like(Comment::getContent, pageParam.getQueryString());
        }
        Page<Comment> commentPage = commentMapper.selectPage(page, queryWrapper);

        PageResult<CommentVo> pageResult = new PageResult<>();
        pageResult.setList(copyList(commentPage.getRecords()));
        pageResult.setTotal(commentPage.getTotal());
        return Result.success(pageResult);
    }
    public List<CommentVo> copyList(List<Comment> commentList) {
        List<CommentVo> commentVoList = new ArrayList<>();
        for (Comment comment : commentList) {
            CommentVo commentVo = new CommentVo();
            commentVo.setId(comment.getId());
            commentVo.setContent(comment.getContent());


            LambdaQueryWrapper<User> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysUserLambdaQueryWrapper.eq(User::getId, comment.getAuthorId());
            commentVo.setUser(userMapper.selectOne(sysUserLambdaQueryWrapper));

            LambdaQueryWrapper<Article> articleLambdaQueryWrapper = new LambdaQueryWrapper<>();
            articleLambdaQueryWrapper.eq(Article::getId, comment.getArticleId());
            commentVo.setArticle(articleMapper.selectOne(articleLambdaQueryWrapper));

            commentVoList.add(commentVo);
        }
        return commentVoList;
    }
    public Result delete(Long id) {
        this.commentMapper.deleteById(id);
        return Result.success(null);
    }

}
